package edu.ayit.controller;

import edu.ayit.pojo.Blog;
import edu.ayit.pojo.Comment;
import edu.ayit.service.BlogService;
import edu.ayit.service.CommentService;
import edu.ayit.service.TagService;
import edu.ayit.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;


    @GetMapping("/")
    public String index(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                        Model model){
        Page<Blog> blogs = blogService.listBlog(pageable);
        model.addAttribute("page",blogs);
        model.addAttribute("types",typeService.getListTop(6));
        model.addAttribute("tags",tagService.getListTop(10));
        model.addAttribute("recommendBlogs",blogService.getListTop(8));
        return "index";
    }

    //全局搜索
    @PostMapping("/search")
    public String search(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                         Model model,
                         @RequestParam String query){
        Page<Blog> blogs = blogService.listBlog(pageable, "%"+query+"%");
        model.addAttribute("page",blogs);
        model.addAttribute("query",query);
        return "search";
    }

    //将数据库中的博客内容取出来，经过转换后发送到博客页面
    @RequestMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
        Blog blog = blogService.getBlogAndConvert(id);
        model.addAttribute("blog",blog);
        return "blog";
    }

    //跳转到归档页面
    @RequestMapping("/archives")
    public String archives(){
        return "archives";
    }

    //每个页面最下面的最新文章推荐
    @GetMapping("/footer/lastBlogs")
    public String lastBlogs(Model model){
        model.addAttribute("lastBlogs",blogService.getListTop(3));
        return "_fragments::lastBlogList";
    }

}
